package com.juyu.miliao.common.security;

import java.io.IOException;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.juyu.miliao.common.msg.ErrorMsg;
import com.juyu.miliao.common.util.ServletTool;

/**
 * 根据请求头中的媒体类型返回对应的结果，
 * 如果是html页面则跳转到登录也，
 * 此外都返回一个json格式的结果
 * @author zc
 *
 */
public class MediaTypeAuthenticationEntryPoint implements AuthenticationEntryPoint{
	private final String loginPageUrl;
	private final ObjectMapper objectMapper;
	private ErrorMsg unauthorizedMsg;
	
	public MediaTypeAuthenticationEntryPoint(ObjectMapper objectMapper, String loginPageUrl){
		this.objectMapper = objectMapper;
		this.loginPageUrl = loginPageUrl;
	}
	
	@Override
	public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException ex)
			throws IOException, ServletException {
		Enumeration<String> headers = request.getHeaders("Accept");
		if(headers.hasMoreElements()){
			String mediaType = headers.nextElement().split(",")[0];
			if(MediaType.TEXT_HTML_VALUE.equals(mediaType)){
				response.sendRedirect(loginPageUrl);
			}
		}
		response.setStatus(HttpStatus.UNAUTHORIZED.value());
		if(unauthorizedMsg != null)
			ServletTool.writeJSONStr(response, objectMapper.writeValueAsString(unauthorizedMsg));
	}
	
	public void setUnauthorizedMsg(ErrorMsg unauthorizedMsg) {
		this.unauthorizedMsg = unauthorizedMsg;
	} 
	
}
